import React, { useCallback, useState, useEffect } from 'react';
import { Table } from 'antd';
import update from 'immutability-helper';
import { DndProvider } from 'react-dnd';
import { HTML5Backend } from 'react-dnd-html5-backend';
import EditRow from './editRow';
import EditCell from './editCell';

import type { TableProps } from 'antd/es/table';

interface EditTable extends TableProps<any> {
  /**
   * 拖拽结束事件
   */
  draged?: (newList: Record<string, any>[]) => void;
}

const Index: React.FC<EditTable> = ({ dataSource = [], ...opt }) => {
  const [data, setData] = useState<Record<string, any>[]>([]);
  const components = {
    body: {
      row: EditRow,
      cell: EditCell,
    },
  };

  const moveRow = useCallback(
    (dragIndex: number, hoverIndex: number) => {
      const dragItem = data[dragIndex];

      if (!dragItem) {
        throw new Error('拖拽的元素没有找到');
      }
      const updateData = update(data, {
        $splice: [
          [dragIndex, 1],
          [hoverIndex, 0, dragItem],
        ],
      });

      opt.draged?.(updateData);
      setData(updateData);
    },
    [data],
  );

  useEffect(() => {
    if (!dataSource) return;
    setData((dataSource ?? []) as Record<string, any>[]);
  }, [dataSource]);

  return (
    <DndProvider backend={HTML5Backend}>
      <Table
        {...opt}
        dataSource={data}
        components={components}
        onRow={(_, index) => {
          const attr = {
            index,
            moveRow,
          };
          return attr as React.HTMLAttributes<any>;
        }}
      />
    </DndProvider>
  );
};

export default Index;
